﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.RBAC.Role;
using ProduceBasicData.Api.DTO.RBACDto;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.RBAC.Role
{
    /// <summary>
    /// 获取角色信息
    /// </summary>
    public class GetRoleHandler : IRequestHandler<GetRoleCommand, ApiPaging<RolesDto>>
    {
        private readonly IBaseRespository<RoleModel> _roleRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roleRepository"></param>
        /// <param name="mapper"></param>
        public GetRoleHandler(IBaseRespository<RoleModel> roleRepository, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<RolesDto>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<RolesDto>();

            try
            {
                // 获取基础查询（排除已删除的数据）
                var role = await _roleRepository.GetAllAsync();
                var query = role.Where(x => x.Isdel == false);

                // 应用查询条件（如果有）
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(x =>
                        x.RoleName != null && x.RoleName.Contains(request.Keyword) ||
                        x.RoleCode != null && x.RoleCode.Contains(request.Keyword));
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    // 应用分页
                    var pagedData = query.OrderByDescending(x => x.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToList();

                    // 映射到DTO
                    result.PageDatas = pagedData.Select(x => new RolesDto
                    {
                        Id = x.Id,
                        RoleName = x.RoleName,
                        RoleCode = x.RoleCode,
                        Description= x.Description,
                        RoleType = x.RoleType,
                        State = x.State,
                        CreateName = x.CreateName,
                        CreateTime = x.CreateTime,
                        UpdateName = x.UpdateName,
                        UpdateTime = x.UpdateTime,
                        Isdel = x.Isdel
                    }).ToList();
                }
                else
                {
                    result.PageDatas = new List<RolesDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "角色查询异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<RolesDto>();
            }

            return result;
        }
    }
}
